﻿function handleAjaxError(jqXHR, textStatus, errorThrown) {
    alert('Возникла ошибка: ' + jqXHR.status + ' ' + errorThrown);
}

function GetRoot() {
    return $("#hdRootUrl").val();
}

function GetDepartmentAddress() {
    GetDepartmentAddressEx($("#DepartmentId").val(), $("#DepartmentAddressId"));
}

function GetDepartmentAddressEx(departmentId, ddlDepartmentAddress) {
    var id = departmentId;

    $.ajax({
        async: false,
        cache: false,
        type: 'POST',
        url: GetRoot() + 'Department/AddressList',
        data: { departmentId: id },
        success: function (result) {
            var ddl = ddlDepartmentAddress;
            ddl.empty();
            if (result.length > 0) {
                $.each(result, function () {
                    ddl.append(
                        $('<option/>')
                            .attr('value', this.Value)
                            .text(this.Text)
                    );
                    if (this.Selected) {
                        ddl.val(this.Value);
                    }
                });
                                
                ddl.prop('disabled', false);
            }
            else {
            }
        },
        error: handleAjaxError
    });
}

function GetPCList() {
    var userId = $("#UserRegisterId").val();
    $.ajax({
        async: false,
        cache: false,
        type: 'POST',
        url: GetRoot() + 'UserRegister/PCList',
        data: { userId: userId },
        success: function (result) {
            var ddl = $("#PCId");
            ddl.empty();
            if (result.length > 0) {
                $.each(result, function (result) {
                    ddl.append(
                                $('<option/>')
                                    .attr('value', this.Value)
                                    .text(this.Text)
                                );
                });
            }
            else {
            }
        },
        error: handleAjaxError
    });
}

function PrepareUserRegisterEdit()
{
    $("#tbUserFullName").autocomplete({
        minLength: 0,
        source: function (request, response) {
            var result = new Array();
            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                url: GetRoot() + "UserRegister/Autocomplete",
                data: { "term": request.term },
                success: function (data) {
                    for (var i = 0; i < data.length ; i++) {
                        result[i] = { label: data[i].FullName, Id: data[i].Id, label2: data[i].Post };
                    }
                },
                error: handleAjaxError
            });
            response(result);
        },
        focus: function (event, ui) {
            return false;
        },
        select: function (event, ui) {
            $(this).data("selectedItem", ui.item);
            SetUserRegister(ui.item.Id, ui.item.label);
            return false;
        }
    })
    .autocomplete("instance")._renderItem = renderItem;

    $('#btnSearch').on('click', function () {
        SearchUsers($("#tbUserFullName").val());
    });

    $("#tbUserFullName").keydown(function (e) {
        if (e.keyCode == 13 && $(this).data("selectedItem") == null) {
            SearchUsers($(this).val());
            e.preventDefault();
        }
        $(this).data("selectedItem", null);
    });
}

var searchUserTerm;
function InitSearchUsersDialog() {
    setFocus($("#LastNameFilter"));
    if (searchUserTerm == null || searchUserTerm.trim() == "")
        return;

    var parts = searchUserTerm.match(/[^ ]+/g);
    $("#LastNameFilter").val(parts[0]);
    if (parts.length > 1) {
        $("#FirstNameFilter").val(parts[1]);
    }
    searchUserTerm = null;
}

function SearchUsers(term) {
    $('#btnSelectUser').trigger("click");
    searchUserTerm = term;
}

function GetSelectedUser(data) {
    SetUserRegister(data.userId, data.userName);
}

function PrepareAutocompleteEdit(idEdit, url) {
    $("#" + idEdit).autocomplete({
        minLength: 1,
        source: function (request, response) {
            var result = new Array();
            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                url: url,
                data: { "term": request.term },
                success: function (data) {
                    for (var i = 0; i < data.length ; i++) {
                        result[i] = { label: data[i].Label, Id: data[i].Id, label2: data[i].Label2 };
                    }
                },
                error: handleAjaxError
            });
            response(result);
        },
        focus: function (event, ui) {
            return false;
        },
        select: function (event, ui) {
            $("#" + idEdit).val(ui.item.label);
            return false;
        },
        change: function (event, ui) {
        }
    })
    .autocomplete("instance")._renderItem = renderItem;
}

function renderItem(ul, item) {
    var content = "<a>" + item.label;
    if (item.label2 != null) {
        content += " (" + item.label2 + ")";
    }
    content += "</a>";
    return $("<li>").append(content).appendTo(ul);
}